#!/usr/bin/python


import Image, ImageDraw
import sys

magic_code = [0x12, 0x34, 0x56, 0x14, 0x36, 0x54, 0x16, 0x34]


def get_point(data, x,y):
    return data[y*valid_width + x]

def get_area_data(data, dx,dy):
    x = dx*4 + 1
    y = dy*4 + 1
    area_data = []
    for row in range(3):
        for col in range(3):
            area_data.append(get_point(data, x+col, y+row))
    return area_data

err_cnt = 0
def get_data(data, index):
    global err_cnt
    row_length = (valid_width-1)/4
    row = index/row_length
    col = index%row_length
    data = get_area_data(data, dx=col, dy=row)
    # check the data ??
    err_flag = False
    for i in data[1:]:
        if i[0] != data[0][0]:
            err_flag = True
            break
    if err_flag == True:
        print "%d error :" % index,
        # print data
        for j in data:
            print "%02x" % j[0],
        print ""
        err_cnt += 1
        if err_cnt > 20:
            exit()
            
    return data[0][0]

# for i in range(1025):
#     val = get_point(i,0)
#     if val == (0,0,255):
        
#     print val


# get the data area, return the start index and size of valid area
def find_magic_code(data):
    for i in range(len(data)-7):
        flag = 1
        for j in range(8):
            if data[i+j][0] != magic_code[j]:
                flag = 0
                break
        if flag == 1:
            # print "index is %d" % i
            width = (data[i+8][0]<<8) | data[i+9][0]
            height = (data[i+10][0]<<8) | data[i+11][0]
            return (i+im_width, width, height)
    return (None, None, None)



# im = Image.open("test.png")     # 
im = Image.open(sys.argv[1])
im_width, im_height = im.size
# assert(im_width == 1025)
# assert(im_height == 769)              # the height of image may be vary
print "image size : %d x %d" % (im_width, im_height)
orig_data = im.getdata()

# find the valid area and crop
start_index, valid_width, valid_height = find_magic_code(orig_data)
if start_index == None:
    print "not matched"
    exit()
print "valid area : %d x %d" % (valid_width, valid_height)
y = start_index / im_width
x = start_index % im_width
valid_im = im.crop((x,y,x+valid_width,y+valid_height))
valid_im.save("valid.png")
valid_data = valid_im.getdata()

# for i in range(20):
#     print get_point(valid_data, i,1),
# print ""
# for i in range(20):
#     print get_point(valid_data, i,2),
# print ""
# for i in range(20):
#     print get_point(valid_data, i,3),
# print ""


# get the length of valid data
valid_length = 0
for i in range(4):
    valid_length |= get_data(valid_data, i)<<((3-i)*8)

print "actual lenght is ",valid_length

recv_data = []    
for i in range(4,4+valid_length):
    # print get_data(valid_data, i)
    recv_data.append(get_data(valid_data, i))


s = ""
for i in recv_data:
    s += chr(i)

#print s
f = open("result", "w")
f.write(s)
f.close()


get_area_data(valid_data, 256, 0)

print err_cnt

exit()


# ==================== first check the data ====================
# for i in range(100):
#     d = get_area_data(i,0)

#     err_flag = False
#     for i in d[1:]:
#         if i != d[0]:
#             err_flag = True
#             break
#     if err_flag == True:
#         print "%d : error"
#     print "%02x" % d[0][0],


# get the magic code
recv_magic_code = []
for index in range(8):
    recv_magic_code.append(get_data(index))

print recv_magic_code
print "===================="
print magic_code

if recv_magic_code != magic_code:
    print "magic code not matched, data corrupt"
    exit(-1)

index += 1
# width
width = (get_data(index) << 8) | get_data(index+1)
index += 2
# get the height
height = (get_data(index) << 8) | get_data(index+1)
index += 2
# get length of data
data_length = 0
for i in range(24,-8,-8):
    data_length |= get_data(index)<<i
    index += 1

print "data_length is %d" % data_length

recv_data = []
for i in range(data_length):
    recv_data.append(get_data(index+i))

f = open("result", "wb")
for d in recv_data:
    f.write(chr(d))
f.close()


print recv_data[-100:]

exit()    







        








# print "the point is %d,%d" % ()


# ptr = 0


# # get the magic code
# recv_magic_code = []
# for i in range(8):
#     recv_magic_code.append(data[ptr][0])
#     ptr += 1


# if recv_magic_code != magic_code:
#     print "magic code not matched, data corrupt"
#     exit(-1)


# get the width
width = (data[ptr][0] << 8) | data[ptr+1][0]
ptr += 2
# get the height
height = (data[ptr][0] << 8) | data[ptr+1][0]
ptr += 2
# get length of data
data_length = 0
for i in range(24,-8,-8):
    data_length |= data[ptr][0]<<i
    ptr += 1


print "valid area is %dx%d" % (width,height)
print "actual data length : %d" % data_length




# y = math.ceil(float(valid_index+1)/im_width) # 
y = (valid_index+1+im_width-1)/im_width - 1
x = valid_index- im_width*y
print (x,y)


# crop and get the valid area
valid_im = im.crop((x,y,x+width-1,y+height-1))
valid_im.save("valid.png")
valid_data = valid_im.getdata()
ptr = 8+4+4                   # the index of actual data


# get the actual data
result = []
for i in range(data_length):
    result.append(chr(valid_data[ptr][0]))
    ptr += 1


# not care the PAD


f = open("result", "wb")
str = ''.join(result)
f.write(str)
f.close()
